<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '#' }">
                运动会比赛成绩管理
            </el-breadcrumb-item>
            <el-breadcrumb-item>
                <a href="#">比赛成绩输出</a>
            </el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box_card">
            <div class="bot_top">
                <div class="top_from">
                    <el-form>
                        <el-form-item label="场号：">
                            <el-select v-model="ttfield">
                                <el-option v-for="i in fieldnum" :key="i" :label="i" :value="i">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="item_name">
                    <el-form>
                        <el-form-item label="项目：">
                            <el-select v-model="ttitem" @change="selItemName">
                                <el-option v-for="(item, index) in gamData" :key="index + 1"
                                    :label="index + 1 + '.' + item.sexName + ' ' + item.gridName + ' ' + item.msidName + ' ' + item.stidName"
                                    :value="item.pmid"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
                <div v-if="totalData.length > 0">
                    <div class="featurebtn">
                        <el-button type="primary" @click="rankCreate">名次生成</el-button>
                        <!-- <el-button type="success" @click="itemSortExcel">项目排序导出</el-button> -->
                        <el-button type="primary" @click="printExcel">打印导出</el-button>
                    </div>
                </div>
                <div class="gradefor">
                    <el-button type="warning" @click="formatting">成绩格式化</el-button>
                </div>
            </div>

            <el-table :data="totalData" border highlight-current-row :header-cell-style="headClass">
                <el-table-column label="名次" align="center">
                    <template #default="scope">
                        {{ scope.row.rnk === 0 ? "" : scope.row.rnk }}
                    </template>
                </el-table-column>
                <el-table-column label="道/组" align="center">
                    <template #default="scope">
                        {{ scope.row.lane + '/' + scope.row.htno }}
                    </template>
                </el-table-column>
                <el-table-column prop="plid1Name" label="姓名" align="center">
                </el-table-column>
                <el-table-column prop="teamName" label="单位" width="180" align="center">
                </el-table-column>
                <el-table-column prop="scoreTime" label="成绩" align="center">
                    <template #default="scope">
                        {{ scope.row.scoreTime === "00:00:00.000" ? "" : scope.row.scoreTime }}
                    </template>
                </el-table-column>
                <el-table-column prop="df" label="分值" align="center">
                    <template #default="scope">
                        {{ scope.row.df === '0' ? "" : scope.row.df }}
                    </template>
                </el-table-column>
                <el-table-column prop="rmark" label="记录" align="center">
                    <template #default="scope">
                        {{ scope.row.rmark === '0' ? "" : scope.row.rmark }}
                    </template>
                </el-table-column>
                <el-table-column label="RT" align="center">
                    <template #default="scope">
                        {{ scope.row.rt === 0 ? "" : scope.row.rt }}
                    </template>
                </el-table-column>
                <el-table-column label="FD2" align="center" v-if="fd.replay === 1 || fd.replay === 3">
                    <template #default="scope">
                        {{ scope.row.fd1 === 0 ? "" : scope.row.fd1 }}
                    </template>
                </el-table-column>
                <el-table-column label="FD3" align="center" v-if="fd.replay === 1 || fd.replay === 3">
                    <template #default="scope">
                        {{ scope.row.fd2 === 0 ? "" : scope.row.fd2 }}
                    </template>
                </el-table-column>
                <el-table-column label="FD4" align="center" v-if="fd.replay === 1 || fd.replay === 3">
                    <template #default="scope">
                        {{ scope.row.fd3 === 0 ? "" : scope.row.fd3 }}
                    </template>
                </el-table-column>
                <el-table-column v-if="poolsize === 25" v-for="i in tableDiatance / 25" :key="i" :label="`${i * 25}`"
                    align="center">
                    <template #default="scope">
                        {{ scope.row['subtime' + (i + 1)] === "00:00:00.000" ? "" : scope.row['subtime' + (i + 1)] }}
                    </template>
                </el-table-column>
                <el-table-column v-if="poolsize === 50" v-for="i in tableDiatance / 50" :key="i" :label="`${i * 50}`"
                    align="center">
                    <template #default="scope">
                        {{ scope.row['subtime' + (i + 1)] === "00:00:00.000" ? "" : scope.row['subtime' + (i + 1)] }}
                    </template>
                </el-table-column>
                <el-table-column prop="noteName" label="备注">
                </el-table-column>
                <el-table-column label="操作" width="100" align="center" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" @click="showeditdialog(scope.row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="paging" @size-change="handleSizeChange" @current-change="handleSizeChange" background
                :page-sizes="[3, 5, 10, 15, 20, 50]" layout="total, prev, pager, next, jumper" :total="total"
                :page-size="queryObj.pageSize" :current-page="queryObj.pageNum">
            </el-pagination>

            <!-- 修改 -->
            <el-dialog class="edit_dialog" title="修改" v-model="editdialogVisible" draggable width="40%"
                :before-close="handleClose">
                <el-form :model="editfrom" label-width="80">
                    <el-form-item label="组：">
                        <el-input v-model="editfrom.htno"></el-input>
                    </el-form-item>
                    <el-form-item label="名次：">
                        <el-input v-model="editfrom.rnk"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名：">
                        <el-input v-model="editfrom.plid1Name"></el-input>
                    </el-form-item>
                    <el-form-item label="单位：">
                        <el-input v-model="editfrom.teamName"></el-input>
                    </el-form-item>
                    <el-form-item label="成绩：">
                        <el-input v-model="editfrom.scoreTime"></el-input>
                    </el-form-item>
                    <el-form-item label="分值：">
                        <el-input v-model="editfrom.df"></el-input>
                    </el-form-item>
                    <el-form-item label="备注：">
                        <el-select v-model="editfrom.note">
                            <el-option label=" " :value="0"></el-option>
                            <el-option v-for="(item, index) in note" :key="index + 1" :label="item"
                                :value="parseInt(index)"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="editfrom.rmark">
                            <el-option v-for="(item, index) in records" :key="index + 1"
                                :label="'平' + item.rtype + '--' + item.smark" :value="item.smark"></el-option>
                            <el-option v-for="(item2, index2) in records" :key="index2 + 1"
                                :label="'破' + item2.rtype + '--' + item2.umark" :value="item2.umark"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancelEdit">取 消</el-button>
                    <el-button type="primary" @click="editConfirm">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import XLSX from 'xlsx'
export default {
    components: {
        XLSX,
    },
    data() {
        return {
            gamData: [],
            queryObj: {
                pageSize: 10,
                pageNum: 1,
                query: ""
            },
            total: 0,
            fieldnum: null,
            poolsize: null,
            ttfield: 1,
            ttitem: 1,
            dataForBackend: {
                chno: 1,
                pmid: 1,
            },
            totalData: [],
            editdialogVisible: false,
            editfrom: {},
            selItem: {},
            tableDiatance: null,
            fd: {},
            note: {},
            records: [],
        }
    },
    created() {
        this.getNoteList();
        this.getGamenameList()
        this.getScheduleinfoList(this.ttfield)
    },
    methods: {
        // 查询
        async getGamenameList() { // 场号
            const result = await this.$http.post(this.BACKEND_URL + '/meeting/getmsg');
            if (result.data.code == 0) {
                this.fieldnum = result.data.data.chcnt
                this.poolsize = result.data.data.poolsize
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        async getNoteList() { // 备注
            const result = await this.$http.post(this.BACKEND_URL + '/result/getstatus');
            if (result.data.code == 0) {
                this.note = result.data.data
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        async postRecordinfoList() { // 记录标识
            const result = await this.$http.post(this.BACKEND_URL + '/Cname/getmsg');
            if (result.data.code == 0) {
                result.data.data.forEach((record) => {
                    if (record.gridtoName === this.fd.gridName) {
                        this.records.push(record);
                    }
                });
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        async getScheduleinfoList(chno) { // 项目
            try {
                const result = await this.$http.post(this.BACKEND_URL + '/show/getmsg', { chno: chno });
                if (result.data.code == 0) {
                    this.gamData = result.data.data
                    if (this.gamData.length === 0) {
                        this.ttitem = null
                        this.totalData = []
                        this.$message.error('无项目')
                    } else {
                        this.gamData.sort((a, b) => a.pmid - b.pmid)
                        this.dataForBackend.pmid = this.gamData[0].pmid
                        this.fd = this.gamData.find(item => item.pmid === this.dataForBackend.pmid)
                        this.postRecordinfoList();
                        this.ttitem = this.gamData[0].pmid
                        this.Getcurrentfulllength()
                        this.getTotalgradeList()
                    }
                } else if (result.data.code == 500) {
                    console.log(result.data.msg)
                }
            } catch (error) {
                if (error === undefined) {
                    this.$message.error('连接错误-获取数据失败');
                }
            }
        },
        async getTotalgradeList() { // 数据
            const result = await this.$http.post(this.BACKEND_URL + '/result/getmsg', { ...this.dataForBackend, ...this.queryObj });
            if (result.data.code == 0) {
                this.totalData = result.data.data
                this.totalData = this.totalData.sort((a, b) => {
                    if (a.htno === 0) {
                        return 1;
                    }
                    if (b.htno === 0) {
                        return -1;
                    }
                    return a.htno - b.htno;
                });
                this.totalData.forEach(item => {
                    for (let key in item) {
                        if (key.startsWith('subtime')) {
                            let date = new Date(item[key]);
                            let hours = date.getUTCHours().toString().padStart(2, '0');
                            let minutes = date.getUTCMinutes().toString().padStart(2, '0');
                            let seconds = date.getUTCSeconds().toString().padStart(2, '0');
                            let milliseconds = date.getUTCMilliseconds().toString().padStart(3, '0');
                            item[key] = `${hours}:${minutes}:${seconds}.${milliseconds}`;
                        }
                    }
                });
                this.total = result.data.total
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        // 获取当前长度
        Getcurrentfulllength() {
            this.selItem = this.gamData.find(item => item.pmid === this.ttitem);
            this.tableDiatance = this.selItem.diatance
        },
        selItemName(val) {
            this.dataForBackend.pmid = val
            this.selItem = this.gamData.find(item => item.pmid === val);
            this.tableDiatance = this.selItem.diatance
            this.fd = this.gamData.find(item => item.pmid === this.dataForBackend.pmid)
            this.getTotalgradeList()
            this.records = []
            this.postRecordinfoList();
        },
        // 名次生成
        async rankCreate() {
            const result = await this.$http.post(this.BACKEND_URL + '/result/setrank', this.dataForBackend);
            if (result.data.code == 0) {
                this.getTotalgradeList()
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        headClass() {
            return { 'background': '#00D2FC', 'color': '#FFFFFF' }
        },
        // 成绩格式化
        formatting() {
            this.$confirm('已有数据已被删除！你确定吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                this.$message({
                    type: 'success',
                    message: '格式化成功!'
                });
                await this.$http.post(this.BACKEND_URL + '/result/reset')
                this.getTotalgradeList()
            }).catch(() => {
            });
        },
        // 转换成绩格式
        formatTime(value) {
            const [hours, minutes, seconds] = value.split(':');
            const milliseconds = (parseInt(hours, 10) * 3600 + parseInt(minutes, 10) * 60 + parseFloat(seconds)) * 1000;
            return milliseconds
        },
        // 修改当前数据
        showeditdialog(info) {
            this.editdialogVisible = true
            this.editfrom = info
        },
        async editConfirm() {
            for (const key in this.editfrom) {
                if (Object.prototype.hasOwnProperty.call(this.editfrom, key) && key.startsWith('subtime')) {
                    const timeStr = this.editfrom[key].split('.')[0];
                    const [hours, minutes, seconds] = timeStr.split(':');
                    const milliseconds = (parseInt(hours, 10) * 3600 + parseInt(minutes, 10) * 60 + parseFloat(seconds)) * 1000; // 计算毫秒数
                    this.editfrom[key] = milliseconds;
                }
            }
            this.editfrom.score = this.formatTime(this.editfrom.scoreTime)
            const result = await this.$http.post(this.BACKEND_URL + '/result/updatemsg', this.editfrom)
            if (result.data.code == 0) {
                this.editdialogVisible = false
                this.$message.success('修改成功')
                this.getTotalgradeList()
            } else if (result.data.code == 500) {
                this.getTotalgradeList()
                this.$message.error(result.data.msg)
            }
        },
        cancelEdit() {
            this.editdialogVisible = false
            this.getTotalgradeList()
        },
        handleClose(done) {
            this.getTotalgradeList()
            done()
        },
        itemSortExcel() {
            console.log('项目排序导出')
        },
        async printExcel() {
            var desiredObject = this.gamData.find(item => item.pmid === this.dataForBackend.pmid);
            var index = this.gamData.indexOf(desiredObject) + 1;
            try {
                const result = await this.$http.post(this.BACKEND_URL + '/result/export1', this.dataForBackend, {
                    responseType: 'blob',
                });
                let downloadUrl = window.URL.createObjectURL(new Blob([result.data]));

                const link = document.createElement('a');
                link.href = downloadUrl;
                link.setAttribute('download', this.dataForBackend.chno + '-' + index + desiredObject.sexName + desiredObject.gridName + desiredObject.msidName + desiredObject.stidName + '.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } catch (error) {
                console.error('File export failed:', error);
            }
        },
        // 分页
        handleSizeChange(newSize) {
            this.queryObj.pageNum = newSize
            this.getTotalgradeList()
        },
    },
    watch: {
        ttfield(newGroupName, oldGroupName) {
            if (newGroupName !== oldGroupName) {
                this.getScheduleinfoList(newGroupName);
                this.dataForBackend.chno = newGroupName
            }
        },
    }
}
</script>

<style lang="less" scoped>
.box_card {
    margin-top: 15px;
}

.edit_dialog {
    .el-select {
        width: 100%;
    }
}

.bot_top{
    display: flex;
    .top_from{
        width: 120px;
    }
}
.item_name {
    width: 280px;
    margin-left: 10px;
}
.featurebtn{
    margin-left: 10px;
}

.gradefor {
    margin-left: auto;
}
.paging {
    margin-top: 15px;
}
</style>